package com.yxy.utils;

import com.alibaba.fastjson.JSON;
import com.yxy.base.BusinessException;
import com.yxy.feign.VO.AdminUserInToken;
import com.yxy.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class TokenCheckUtil {
  @Autowired
  private RedisUtils redisUtils;

  //存储 不需要验证token的url列表
  private static List<String> noAuthUrls = new ArrayList<>();

  static {
    noAuthUrls.add("/hello/sayHello");// 心跳检查接口,无需验证token
    noAuthUrls.add("/file/upload");// 心跳检查接口,无需验证token
    noAuthUrls.add("/file/downloadFile");// 心跳检查接口,无需验证token
  }

  //根据token获取登陆用户信息
  public AdminUserInToken getUserInfoByToken() throws BusinessException {
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    String requestURI = request.getRequestURI();
    System.out.println("requestURI---->" + requestURI);
    // 放行某些url,不验证token
    if (noAuthUrls.contains(requestURI)) {
      return null;
    }
    String token = request.getHeader("X-Token");
    if (StringUtils.isEmpty(token)) {
      throw new BusinessException(403, "token不能为空");
    }

    String adminUserStr = redisUtils.get(token);
    if (adminUserStr == null) {
      throw new BusinessException(403, "token无效");
    }
    AdminUserInToken curUser = JSON.parseObject(adminUserStr, AdminUserInToken.class);
    return curUser;
  }

  // 工具方法, 获取invoke_union_auth_token用于调用union auth接口
  public String getInvokeUnionAuthToken() {
    String invokeUnionAuthToken = redisUtils.get("invoke_union_auth_token");
    if (!StringUtils.isEmpty(invokeUnionAuthToken)) {
      return invokeUnionAuthToken;
    } else { //如果redis中该项为空, 则生成一个保存到redis中
      log.info("redis中app调用union auth的token为空, 则生成一个");
      invokeUnionAuthToken = CommonUtils.generateUUID();
      redisUtils.setEx("invoke_union_auth_token", invokeUnionAuthToken, 60*60*24);//有效期1天
      return invokeUnionAuthToken;
    }
  }
}
